<template>
  <div class="wrapper">
    <div class="main" v-loading="loading">
      <div class="search-bar">
        <div>
          <el-button type="primary" size="mini" @click="openEditDialog" :disabled="!hasAuthority">新增</el-button>
          <!-- <el-button type="primary" size="mini" @click="clickDelPlan(false)" :disabled="multipleSelection.length === 0 || !hasAuthority">批量删除</el-button> -->
          <el-button type="primary" size="mini" @click="$refs.uploadInput.click()" :disabled="!hasAuthority">导入生产计划</el-button>
          <el-button type="primary" size="mini" @click="uploadPiecework(false)" :disabled="!hasAuthority">导入生产订单</el-button>
          <el-dropdown>
            <el-button type="primary" size="mini">
              模板导出<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="exportPlan">导出生产计划模板</el-dropdown-item>
              <el-dropdown-item @click.native="exportWarehousing">导出计件单模板</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <input ref="uploadInput" type="file" style="display: none;" @change="uploadFile($event)">
          <input ref="uploadInput2" type="file" style="display: none;" @change="uploadFile2($event)">
        </div>
        <span class="filter" @click="showSearchPanel = !showSearchPanel">
          <span>筛选<img src="../../../../assets/livolobim/filter.png"></span>
          <div class="dot" v-show="hasSearchCondition"></div>
        </span>
        <el-drawer
          title="筛选"
          :visible.sync="showSearchPanel"
          :withHeader="false"
          size="500">
          <div style="display: flex; flex-direction: column; height: 100vh; padding-bottom: 30px;">
            <el-form label-width="120px" label-position="top" style="flex: 1;">
              <div style="font-size: 16px; line-height: 50px; font-weight: bold; border-bottom: 1px solid #DCDFE6; padding: 0 20px;">筛选</div>
              <div style="padding: 0 20px; margin-top: 20px; min-height: 400px; overflow-y: auto;">
                <el-form-item label="单据编号：">
                  <el-input v-model="searchPost.planNumber" placeholder="请输入单据编号" clearable></el-input>
                </el-form-item>
                <el-form-item label="计划名称：">
                  <el-input v-model="searchPost.planName" placeholder="请输入计划名称" clearable></el-input>
                </el-form-item>
                <el-form-item label="计划完工日期：">
                  <el-col :span="11">
                    <el-date-picker type="date" placeholder="请选择起始日期" v-model="searchPost.planFinishTimeStart" style="width: 100%;"></el-date-picker>
                  </el-col>
                  <el-col style="text-align: center;" :span="2">-</el-col>
                  <el-col :span="11">
                    <el-date-picker type="date" placeholder="请选择截止日期" v-model="searchPost.planFinishTimeEnd" style="width: 100%;"></el-date-picker>
                  </el-col>
                </el-form-item>
                <el-form-item label="搜索类型：">
                  <el-select v-model="searchPost.searchType" placeholder="请选择搜索类型" style="width: 100%;">
                    <el-option value="0" label="全部"></el-option>
                    <el-option value="1" label="当前用户"></el-option>
                  </el-select>
                </el-form-item>
              </div>
            </el-form>
            <div style="min-height: 40px; display: flex; padding: 0 20px;">
              <el-button @click="resetSearchPost" style="width: 50%">重置</el-button>
              <el-button type="primary" @click="getPlanList(true)" style="width: 50%">查询</el-button>
            </div>
          </div>
        </el-drawer>
      </div>
      <div class="table">
        <el-table ref="singleTable" highlight-current-row :height="tableHeight+'px'" :data="tableData" @selection-change="handleSelectionChange" @current-change="handleCurrentChange" border style="width: 100%" @row-click="searchPlan">
          <el-table-column
            type="selection"
            align="center"
            width="55">
          </el-table-column>
          <el-table-column label="序号" align="center" width="80" type="index"></el-table-column>
          <el-table-column prop="planBelongName" label="所属模块" align="center" min-width="120"></el-table-column>
          <el-table-column prop="planNumber" label="单据编号" align="center" min-width="120"></el-table-column>
          <el-table-column prop="planName" label="计划名称" align="center" min-width="120"></el-table-column>
          <el-table-column prop="planOrderCompleted" label="完工数量" align="center" min-width="120"></el-table-column>
          <el-table-column label="未完工数量" align="center" min-width="120">
            <template slot-scope="scope">
              <span>{{Number(scope.row.planOrderVolume)-Number(scope.row.planOrderCompleted)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="planOrderVolume" label="计划订单总量" align="center" min-width="120"></el-table-column>
          <el-table-column label="单据状态" align="center" min-width="80">
            <template slot-scope="scope">
              <span>{{planStatus[Number(scope.row.planStatus)-1]}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="planFinishTime" label="计划完工日期" align="center" min-width="120"></el-table-column>
          <el-table-column prop="planRealFinishTime" label="实际完工日期" align="center" min-width="120"></el-table-column>
          <el-table-column prop="planPrincipalName" label="负责人" align="center" min-width="100"></el-table-column>
          <el-table-column label="操作" align="center" min-width="250">
            <template slot-scope="scope">
              <el-button @click.native.prevent="openEditDialog(scope)" :disabled="!hasAuthority && scope.row.canAddWarehousing !=='1' " type="text" size="small">编辑</el-button>
              <el-button @click.native.prevent="delPlan(scope.row)" :disabled="!hasAuthority" type="text" size="small">删除</el-button>
              <el-button type="text" size="small" @click.native.prevent="uploadPiecework(scope.row.planNumber)" :disabled="scope.row.canAddWarehousing !== '1' || scope.row.planStatus !== '1'">导入生产订单</el-button>
              <el-button type="text" size="small" @click.native.prevent="openAddPieceWorkDialog(scope.row)" :disabled="scope.row.canAddWarehousing !== '1' || scope.row.planStatus !== '1'">计件</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="bottom">
        <div class="btn-wrapper"></div>
        <el-pagination background layout="prev, pager, next" :total="pageConfig.totalCount" :page-size="pageConfig.pageSize" :current-page.sync="pageConfig.pageIndex" @current-change="currentChangeHandle"></el-pagination>
      </div>
      <div class="table" style="padding-top: 15px; border-top: 2px solid #DCDFE6;">
        <el-table :height="(tableHeight-15)+'px'" :data="tableData2" border style="width: 100%">
          <el-table-column label="序号" align="center" width="80">
            <template slot-scope="scope">{{scope.$index+1}}</template>
          </el-table-column>
          <el-table-column prop="warehousingBoxNumber" label="分箱号" align="center" min-width="120"></el-table-column>
          <el-table-column prop="warehousingProductId" label="产品编号" align="center" min-width="120"></el-table-column>
          <el-table-column prop="warehousingProductName" label="产品名称" align="center" min-width="200"></el-table-column>
          <el-table-column prop="warehousingRealNumber" label="实际入库数量" align="center" min-width="120"></el-table-column>
          <el-table-column prop="warehousingCreatorName" label="发起人" align="center" min-width="120"></el-table-column>
          <el-table-column prop="warehousingModifyTime" label="操作日期" align="center" min-width="120"></el-table-column>
          <el-table-column label="单据状态" align="center" min-width="120">
            <template slot-scope="scope">
              <span>{{warehousingStatus[Number(scope.row.warehousingStatus)]}}</span>
            </template>
          </el-table-column>
          <el-table-column label="当前处理人" align="center" min-width="100">
            <template slot-scope="scope">
              <span>{{(scope.row.warehousingStatus === '0' || scope.row.warehousingStatus === '') ? '' : scope.row.warehousingStatus === '1' ? scope.row.warehousingQualityAuditName : scope.row.warehousingStatus === '2' ? scope.row.warehousingSignForName : scope.row.warehousingInputName}}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" min-width="180">
            <template slot-scope="scope">
              <el-button @click.native.prevent="openEditPieceWorkDialog(scope, 'edit')" type="text" size="small" v-if="scope.row.canModifyData==='1' && scope.row.warehousingStatus==='1'">编辑</el-button>
              <el-button @click.native.prevent="openEditPieceWorkDialog(scope, 'edit')" type="text" size="small" v-if="(!scope.row.warehousingCreatorId || (scope.row.warehousingCreatorId && scope.row.warehousingCreatorId === userInfo.dingId)) && (scope.row.warehousingStatus==='0' || scope.row.warehousingStatus==='')">计件单确认</el-button>
              <el-button @click.native.prevent="openEditPieceWorkDialog(scope, 'check')" type="text" size="small" v-if="(scope.row.warehousingStatus==='1' && (userInfo.dingId===scope.row.warehousingQualityAuditId)) || (scope.row.warehousingStatus==='2' && (userInfo.dingId===scope.row.warehousingSignForId)) || (scope.row.warehousingStatus==='3' && (userInfo.dingId===scope.row.warehousingInputId))">审核</el-button>
              <el-button @click.native.prevent="openEditPieceWorkDialog(scope, 'view')" type="text" size="small">查看</el-button>
              <el-button @click.native.prevent="delData(scope)" type="text" size="small" v-if="scope.row.canDeleteData==='1'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-dialog :title="!form.id ? '新增生产计划' : '编辑生产计划'" :visible.sync="dialogVisible" width="800px">
      <div style="max-height: 500px; overflow:auto; padding: 0 20px;">
        <el-form label-width="150px" label-position="left">
          <el-form-item label="单据编号">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-input v-model="form.planNumber" placeholder="请输入单据编号" :disabled="!!form.id"></el-input>
          </el-form-item>
          <el-form-item label="计划名称">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-input v-model="form.planName" placeholder="请输入计划名称"></el-input>
          </el-form-item>
          <el-form-item label="计划内容">
            <el-input v-model="form.planContent" placeholder="请输入计划内容" type="textarea"></el-input>
          </el-form-item>
          <el-form-item label="确认采购/生产日期">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-date-picker type="date" placeholder="选择日期" v-model="form.planProcurementTime" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="计划到货/完工日期">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-date-picker type="date" placeholder="选择日期" v-model="form.planFinishTime" style="width: 100%"></el-date-picker>
          </el-form-item>
          <el-form-item label="负责人">
            <div class="select-btn" @click="selectDingUsers"><span><i class="el-icon-plus"></i></span>添加</div>
            <div class="select-btn" style="padding: 0;" @click="delMember" v-if="form.planPrincipalName">{{form.planPrincipalName}}<div class="del">移除</div></div>
          </el-form-item>
          <el-form-item label="所属模块">
            <el-select ref="planBelongIdSelected" v-model="form.planBelongId" filterable placeholder="请选择所属模块" style="width: 100%;">
              <el-option v-for="item in subDictList.process" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单据类型">
            <el-select v-model="form.planDatatype" filterable placeholder="请选择单据类型" style="width: 100%;">
              <el-option v-for="item in subDictList.planDatatype" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投放类型">
            <el-select v-model="form.planDeliveryType" filterable placeholder="请选择投放类型" style="width: 100%;">
              <el-option v-for="item in subDictList.planDeliveryType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="投放单据类型">
            <el-select v-model="form.planDeliveryDocumenttype" filterable placeholder="请选择投放单据类型" style="width: 100%;">
              <el-option v-for="item in subDictList.planDeliveryDocumenttype" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料编码">
            <el-select ref="labelSelected" v-model="form.planMaterialCode" filterable placeholder="请选择物料编码或物料名称" style="width: 100%;">
              <el-option v-for="item in subDictList.planMaterial" :key="item.id" :label="item.value" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="物料名称">
            <el-select ref="labelSelected" v-model="form.planMaterialCode" filterable placeholder="请选择物料编码或物料名称" style="width: 100%;">
              <el-option v-for="item in subDictList.planMaterial" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单位">
            <el-select v-model="form.planUnit" filterable placeholder="请选择单位" style="width: 100%;">
              <el-option v-for="item in subDictList.planUnit" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="确认订单量">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-input v-model="form.planOrderVolume" placeholder="请输入确认订单量" type="number" min="0" @wheel.native.prevent="stopScrollFun($event)"></el-input>
          </el-form-item>
          <el-form-item label="数据来源">
            <el-select v-model="form.planSourceType" filterable placeholder="请选择数据来源" style="width: 100%;">
              <el-option v-for="item in subDictList.planSourceType" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="运算编号">
            <el-input v-model="form.planSourceNumber" placeholder="请输入运算编号"></el-input>
          </el-form-item>
          <el-form-item label="需求单据编号">
            <el-input v-model="form.planDemandNumber" placeholder="请输入需求单据编号"></el-input>
          </el-form-item>
          <el-form-item label="需求单据行号">
            <el-input v-model="form.planDemandLineNumber" placeholder="请输入需求单据行号"></el-input>
          </el-form-item>
          <el-form-item label="单据状态" v-if="form.id">
            <span style="color: red; position:absolute; left: -160px;">*</span>
            <el-select v-model="form.planStatus" placeholder="请选择单据状态" style="width: 100%;">
              <el-option value="1" label="执行"></el-option>
              <el-option value="2" label="完成"></el-option>
              <el-option value="3" label="终止"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" style="display: flex; justify-content: space-between;">
        <div></div>
        <div>
          <el-button @click="dialogVisible = false" size="mini">取消</el-button>
          <el-button type="primary" size="mini" @click="submitForm">提交</el-button>
        </div>
      </span>
    </el-dialog>
    <AddOrEdit ref="AddOrEdit" @refreshList="refreshData" />
  </div>
</template>

<script>
import dingMixin from  '@/mixins/ding'
import formUtil from '@/utils/formUtil'
import AddOrEdit from '../storage/add-or-edit'
export default {
  data () {
    return {
      tableHeight: '',
      dialogVisible: false,
      pageConfig:{
        pageIndex: 1,
        pageSize: 15,
        totalCount: 0
      },
      searchPost: {
        planNumber: '',
        planName: '',
        planFinishTimeStart: null,
        planFinishTimeEnd: null,
        searchType: '0',
      },
      searchPostInit: {
        planNumber: '',
        planName: '',
        planFinishTimeStart: null,
        planFinishTimeEnd: null,
        searchType: '0',
      },
      subDictList: {
        planDatatype: [],
        planDeliveryType: [],
        planDeliveryDocumenttype: [],
        planMaterialCode: [],
        planMaterialName: [],
        planUnit: [],
        planSourceType: [],
        process: []
      },
      planDatatype: [],
      tableData: [],
      form: {
        planNumber: '',
        planName: '',
        planContent: '',
        planProcurementTime: '',
        planFinishTime: '',
        planDatatype: '',
        planDeliveryType: '',
        planDeliveryDocumenttype: '',
        planMaterialCode: '',
        planMaterialName: '',
        planUnit: '',
        planOrderVolume: '',
        planSourceType: '',
        planSourceNumber: '',
        planDemandNumber: '',
        planDemandLineNumber: '',
        planStatus: '',
        planPrincipalId: '',
        planPrincipalName: '',
        planBelongId: '',
        planBelongName: '',
        warehousingBoxNumber: '',
      },
      multipleSelection: [],
      tableData2: [],
      warehousingStatus: ['计件单待确认', '待品质审批', '待签收', '待erp录入', 'erp录入完成'],
      planStatus: ['执行', '完成', '终止'],
      addDialogVisible: false,
      authorityAsd: {},
      showSearchPanel: false,
      currentRow: null,
      planId: '',
      loading: false,
    };
  },
  components: {
    AddOrEdit
  },
  mixins: [dingMixin],
  mounted () {
    this.tableHeight = (document.documentElement['clientHeight'] - 200) / 2
    window.onresize = () => {
      this.tableHeight = (document.documentElement['clientHeight'] - 200) / 2
    }
    this.getAuthorityAsd();
    this.getDictList();
    this.getPlanList(true);
  },
  computed: {
    hasAuthority() {
      return this.authorityAsd.userLevel === '1' || this.authorityAsd.userLevel === '2'
    },
    hasSearchCondition() {
      return JSON.stringify(this.searchPost) !== JSON.stringify(this.searchPostInit)
    }
  },
  watch: {
    searchPost: {
      handler() {
        this.getPlanList(true)
      },
      deep: true
    }
  },
  methods: {
    async getAuthorityAsd() {
      this.authorityAsd = await this.$httpN.postB('pc/authority/asd')
    },
    async getDictList() {
      let {list} = await this.$httpN.postB('pc/dict/list', {
        searchType: '1',
        limit: 999
      });
      list.forEach((item, index) => {
        this.getSubDictList(item);
      })
    },
    async getSubDictList(item) {
      let {list} = await this.$httpN.postB('pc/dict/list', {pid: item.id, limit: 999})
      //所属模块-计件入库功能模块
      if(item.id === '1293101384636657666') {
        this.subDictList.process = list.filter(element => {
          return element.id !== '1293102120648929281'
        })
      }
      if(item.id === '1293795021783601154') this.subDictList.planDatatype = list      //计划类型
      if(item.id === '1293798715161690114') this.subDictList.planDeliveryType = list  //计划投放类型
      if(item.id === '1293799123288444929') this.subDictList.planDeliveryDocumenttype = list   //计划投放单据类型
      if(item.id === '1293800164935454721') this.subDictList.planMaterial = list //物料
      if(item.id === '1293800896178802690') this.subDictList.planUnit = list     //单位
      if(item.id === '1293801422798835714') this.subDictList.planSourceType = list //计划数据来源
    },
    currentChangeHandle (val) {
      this.pageConfig.pageIndex = val
      this.getPlanList()
    },
    async getPlanList(type) {
      if(type) this.pageConfig.pageIndex = 1;
      var planFinishTimeStart = '';
      var planFinishTimeEnd = '';
      if(this.searchPost.planFinishTimeStart) planFinishTimeStart = new Date(this.searchPost.planFinishTimeStart).getFullYear() + '-' + (new Date(this.searchPost.planFinishTimeStart).getMonth()+1) + '-' + new Date(this.searchPost.planFinishTimeStart).getDate();
      if(this.searchPost.planFinishTimeEnd) planFinishTimeEnd = new Date(this.searchPost.planFinishTimeEnd).getFullYear() + '-' + (new Date(this.searchPost.planFinishTimeEnd).getMonth()+1) + '-' + new Date(this.searchPost.planFinishTimeEnd).getDate();
      let {list, totalCount} = await this.$httpN.postB('pc/plan/list',{
        page: this.pageConfig.pageIndex,
        limit: this.pageConfig.pageSize,
        planNumber: this.searchPost.planNumber,
        planName: this.searchPost.planName,
        planFinishTimeStart: planFinishTimeStart,
        planFinishTimeEnd: planFinishTimeEnd,
        searchType: this.searchPost.searchType,
      });
      this.tableData = list
      this.pageConfig.totalCount = totalCount
    },
    openEditDialog(data) {
      formUtil.resetData(this.form);
      data.row ? this.form = JSON.parse(JSON.stringify(data.row)) : this.form.planStatus = '1'
      this.dialogVisible = true;
    },
    async submitForm() {
      if(!this.form.planNumber) return this.$message.error('请输入单据编号');
      if(!this.form.planName) return this.$message.error('请输入计划名称');
      // if(!this.form.planContent) return this.$message.error('请输入计划内容');
      if(!this.form.planProcurementTime) return this.$message.error('请选择确认采购或生产日期');
      if(!this.form.planFinishTime) return this.$message.error('请选择确认到货或完日期');
      if(new Date(this.form.planProcurementTime) - new Date(this.form.planFinishTime) > 0 ) return this.$message.error('截止日期不可小于开始日期');
      // if(!this.form.planPrincipalId) return this.$message.error('请选择负责人');
      // if(!this.form.planDatatype) return this.$message.error('请选择计划类型');
      // if(!this.form.planDeliveryType) return this.$message.error('请选择计划投放类型');
      // if(!this.form.planDeliveryDocumenttype) return this.$message.error('请选择计划单据投放类型');
      // if(!this.form.planMaterialCode) return this.$message.error('请选择计划物料');
      // if(!this.form.planUnit) return this.$message.error('请选择单位');
      if(!this.form.planOrderVolume) return this.$message.error('请输入确认订单量');
      // if(!this.form.planSourceType) return this.$message.error('请选择计划数据来源');
      // if(!this.form.planSourceNumber) return this.$message.error('请输入数据来源编号');
      // if(!this.form.planDemandNumber) return this.$message.error('请输入需求编号');
      // if(!this.form.planDemandLineNumber) return this.$message.error('请输入需求单据行号');
      if(this.form.planDemandLineNumber.length > 4) return this.$message.error('需求单据行号最大长度是4位');
      if(!this.form.planStatus) return this.$message.error('请选择单据状态');
      this.form.planMaterialCode ? this.form.planMaterialName = this.$refs['labelSelected'].selectedLabel : this.form.planMaterialName = '';
      this.form.planBelongId ? this.form.planBelongName = this.$refs['planBelongIdSelected'].selectedLabel : this.form.planBelongName = '';

      var data = {
        planNumber: this.form.planNumber,
        planName: this.form.planName,
        planPrincipalId: this.form.planPrincipalId,
        planPrincipalName: this.form.planPrincipalName,
        planBelongId: this.form.planBelongId,
        planBelongName: this.form.planBelongName,
        planContent: this.form.planContent,
        planProcurementTime: this.form.planProcurementTime,
        planFinishTime: this.form.planFinishTime,
        planDatatype: this.form.planDatatype,
        planDeliveryType: this.form.planDeliveryType,
        planDeliveryDocumenttype: this.form.planDeliveryDocumenttype,
        planDemandLineNumber: this.form.planDemandLineNumber,
        planMaterialCode: this.form.planMaterialCode,
        planMaterialName: this.form.planMaterialName,
        planUnit: this.form.planUnit,
        planOrderVolume: this.form.planOrderVolume,
        planSourceType: this.form.planSourceType,
        planSourceNumber: this.form.planSourceNumber,
        planDemandNumber: this.form.planDemandNumber,
        planStatus: this.form.planStatus
      }
      if(this.form.id) data.id = this.form.id
      if(!await this.$httpN.postB(!this.form.id ? 'pc/plan/save' : 'pc/plan/update', data)) return
      formUtil.submitSuccess('保存成功');
      this.getPlanList(true);
      this.tableData2 = [];
      this.dialogVisible = false;
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    async clickDelPlan(data) {
      let ids = data ? [data.id] : this.multipleSelection.map(item => item.id);
      let planNumbers = data ? [data.planNumber] : this.multipleSelection.map(item => item.planNumber);
      formUtil.submitConfirm('请问您是否确定删除计划？', async ()=> {
        if(!await this.$httpN.postB('pc/plan/delete', {ids: ids.join(','), planNumbers: planNumbers.join(',')})) return;
        formUtil.submitSuccess('删除成功');
        this.getPlanList(true);
        this.tableData2 = [];
      })
    },
    async delPlan(data) {
      //判断该生产计划下是否存在计件单，有就不能删
      let {list} = await this.$httpN.postB('pc/warehousing/list', {warehousingPlanId: data.planNumber,page: 1,limit: 1})
      if(list.length>0) {
        formUtil.submitConfirm('选择的生产计划的下存在生产订单，请问您是否确认全部删除？', async ()=> {
          if(!await this.$httpN.postB('pc/plan/delete', {ids: data.id, planNumbers: data.planNumber})) return;
          formUtil.submitSuccess('删除成功');
          this.getPlanList(true);
          this.tableData2 = [];
        })
      } else {
        formUtil.submitConfirm('请问您是否确定删除计划？', async ()=> {
          if(!await this.$httpN.postB('pc/plan/delete', {ids: data.id, planNumbers: data.planNumber})) return;
          formUtil.submitSuccess('删除成功');
          this.getPlanList(true);
          this.tableData2 = [];
        })
      }
    },
    async exportPlan() {
      let fileData = await this.$httpN.get('pc/plan/templateExport', {}, 'blob');
      this.downFile(fileData, '生产计划模板.xls');
    },
    async exportWarehousing() {
      let fileData = await this.$httpN.get('pc/warehousing/templateExport', {}, 'blob');
      this.downFile(fileData, '计件单模板.xls');
    },
    downFile(blob, fileName) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, fileName);
      } else {
        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
        window.URL.revokeObjectURL(link.href);
      }
    },
    uploadFile(e) {
      this.loading = true;
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      formData.append("name", 'file');
      this.$httpN.upload('pc/plan/fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          formUtil.submitSuccess('上传成功')
          this.getPlanList(true);
          if(res.data.data.errorData) {
            let errorData = res.data.data.errorData.replace(/\s*/g,"")
            let errorDataList = errorData.split(';')
            errorDataList.forEach((item, errorIdx) => {
              if(item !== '') errorDataList[errorIdx] = '<p>' + item + '</p>'
              return item !== ''
            })
            this.$alert(errorDataList.join(''), '注意', {
              dangerouslyUseHTMLString: true
            })
          }else if(res.data.data.failData) {
            let failDataList = res.data.data.failData.split(',')
            failDataList.forEach((item, idx) => {
              if(item !== '') failDataList[idx] = '<p>' + item + '</p>'
              return item !== ''
            })
            this.$alert(failDataList.join('')+'导入失败', '注意', {
              dangerouslyUseHTMLString: true
            })
          }
        }else{
          this.$message.error('上传文件出错,请重试')
        }
        this.loading = false;
      })
      e.target.value = '';
    },
    uploadPiecework(planNumber) {
      this.planId = planNumber ? planNumber : ''
      this.$refs.uploadInput2.click()
    },
    uploadFile2(e) {
      this.loading = true;
      let file = e.target.files[0];
      var formData = new FormData();
      formData.append("file", file);
      if(!!this.planId) formData.append("planId", this.planId);
      formData.append("name", 'file');
      this.$httpN.upload('pc/warehousing/fileUpload', formData).then((res) => {
        if(res.status === 200 && res.data.code === 0) {
          if (res.data.data.errorMessage) return this.$message.error(res.data.data.errorMessage)
          formUtil.submitSuccess('上传成功')
          this.getPlanList(true);
          if(res.data.data.jumpData) {
            let errorDataList = res.data.data.jumpData.split(',')
            errorDataList.forEach((item, errorIdx) => {
              if(item !== '') {
                let arr = item.split(':')
                errorDataList[errorIdx] = `<p>文件“${arr[0]}”，单据编号为“${arr[1]}”下已有计件单，导入失败</p>`
              }
              return item !== ''
            })
            this.$alert(errorDataList.join(''), '注意', {
              dangerouslyUseHTMLString: true
            })
          }
        }else{
          this.$message.error('上传文件出错,请重试')
        }
        this.loading = false;
      })
      e.target.value = '';
    },
    delMember() {
      this.form.planPrincipalId = ''; 
      this.form.planPrincipalName = '';
    },
    selectDingUsers(){
      this.complexPicker(1, [], []).then((data)=>{
        this.form.planPrincipalId = data.map(item => item.emplId).join(',');
        this.form.planPrincipalName = data.map(item => item.name).join(',');
      })
    },
    async searchPlan(row) {
      this.planId = row.planNumber;
      let {list} = await this.$httpN.postB('pc/warehousing/list', {
        warehousingPlanId: row.planNumber,
        page: 1,
        limit: 999,
      })
      this.tableData2 = list;
    },
    openAddPieceWorkDialog(data) {
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.$refs.AddOrEdit.init(false, data.planBelongId, data.planBelongName, 'add', data.planNumber);
      })
    },
    openEditPieceWorkDialog(data, operation) {
      let warehousingBelongId = data.row.warehousingBelongId ? data.row.warehousingBelongId : this.currentRow.planBelongId ? this.currentRow.planBelongId : ''
      let warehousingBelongName = data.row.warehousingBelongName ? data.row.warehousingBelongName : this.currentRow.planBelongName ? this.currentRow.planBelongName : ''
      // let warehousingBelongId = data.row.warehousingBelongId
      // let warehousingBelongName = data.row.warehousingBelongName
      this.addDialogVisible = true
      this.$nextTick(() => {
        this.$refs.AddOrEdit.init(data.row.id, warehousingBelongId, warehousingBelongName, operation);
      })
    },
    async refreshData() {
      if(this.currentRow) {
        this.searchPlan(this.currentRow);
        let temp = await this.$httpN.postB('pc/plan/info', {id: this.currentRow.id})
        this.tableData.forEach((item, index) => {
          if(item.id === temp.id) this.$set(this.tableData[index], 'planOrderCompleted', temp.planOrderCompleted)
        })
      }
    },
    async delData(data) {
      formUtil.submitConfirm('请问您是否确定删除这条记录？', async ()=> {
        if(!await this.$httpN.postB('pc/warehousing/delete', {ids: data.row.id, warehousingBelongName: data.row.warehousingBelongName})) return;
        formUtil.submitSuccess('删除成功');
        this.refreshData();
      })
    },
    resetSearchPost() {
      this.searchPost = JSON.parse(JSON.stringify(this.searchPostInit))
      this.getPlanList(true)
    },
    stopScrollFun(evt) {
      evt = evt || window.event;
      if(evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble=true;
        evt.returnValue = false;
      }
      return false;
    },
  }
}
</script>

<style lang='scss' scoped>
.wrapper {
  height: 100%;
  width: 100%;
  .main {
    height: 100%;
    padding: 15px 0;
    .search-bar {
      padding: 0 15px 15px 15px;
      display: flex;
      justify-content: space-between;
      position: relative;
      .filter {
        font-size: 14px;
        cursor: pointer;
        margin-top: 8px;
        color: #909399;
        position: relative;
        line-height: 14px;
        span {
          display: inline-block;
        }
        img {
          width: 14px;
          height: 14px;
          position: relative;
        }
        .dot {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #4983FF;
          display: inline-block;
          vertical-align: super;
        }
      }
    }
    .table {
      overflow: auto;
      padding: 0 15px;
    }
    .bottom {
      height: 54px;
      padding: 13px 15px;
      display: flex;
      justify-content: space-between;
      .btn-wrapper {
        white-space: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        &::-webkit-scrollbar {
          width: 4px;
          height: 4px;
        }
        &::-webkit-scrollbar-thumb {/*滚动条里面小方块*/
          border-radius: 5px;
          background: rgba(0,0,0,0.2);
          scrollbar-arrow-color:red;
        }
        &::-webkit-scrollbar-track {/*滚动条里面轨道*/
          border-radius: 0;
          background: rgba(0,0,0,0.1);
        }
      }
    }
  }
}
.select-btn{
  float:left;
  font-weight: normal;
  margin-right: 5px;
  margin-bottom: 10px;
  width: 80px;
  height: 28px;
  border-radius: 30px;
  background: #FAFAFA;
  border: 1px solid #ECECEC;
  position: relative;
  padding-left: 21px;
  line-height: 28px;
  color: #7982A7;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
  span{
    position: absolute;
    top: 1px;
    left: 1px;
    display:block;
    height: 24px;
    width: 24px;
    background: #CACACA;
    color: white;
    border-radius: 50%;
    text-align: center;
    line-height: 24px;
    img{
      width: 24px;
      height: 24px;
      border-radius: 50%;
    }
  }
  .del{
    position: absolute;
    top:0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 30px;
    color: white;
    text-align: center;
    background:rgba(130, 130, 130, 0.9);
    display: none;
  }
  &:hover{
    .del, .close{
      display: block;
    }
  }
}
</style>